package com.lk.demo.service;


import com.lk.demo.model.Author;
import com.lk.demo.model.Book;
import com.lk.demo.repos.AuthorRepository;
import com.lk.demo.repos.BookRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BookService {

    @Autowired
    private BookRepository bookRepository;
    @Autowired
    private AuthorRepository authorRepository;
    private static final Logger log = LoggerFactory.getLogger(BookService.class);
    public Book get(Long id) {
        return bookRepository.findById(id).orElse(null);
    }



    public List<Book> findBooks(String name, String author) {
        List<Book>  books = bookRepository.findBooks(name, author);
        for(Book book: books){
            // 触发懒加载
            List<Author> as =book.getAuthors();
            for(Author a: as){}
        }
        return books;
    }

    public Book save(Book book) {
       return bookRepository.save(book);
    }

    public Book update(Book book) {
        // do something
        if(book.getId() <= 0){
            log.error("not find this book by id: {}", book.getId());
        }
        return bookRepository.save(book);
    }

    public String delete(Long id) {
        log.warn("{} deleted", id);
        bookRepository.deleteById(id);
        return "delete book id:" + id;
    }

    public List<Author> addAuthor(Long bookId, Long authorId) {
        bookRepository.findById(bookId).ifPresent(book -> {
          authorRepository.findById(authorId).ifPresent(author -> {
              if(!book.getAuthors().contains(author)){
                  book.getAuthors().add(author);
                  bookRepository.save(book);
              }
            });
        });
      Book book =bookRepository.findById(bookId).orElse(null);
      return book==null?null:book.getAuthors();
    }

    public List<Author> deleteAuthor(Long bookId, Long authorId) {
        bookRepository.findById(bookId).ifPresent(book -> {
            authorRepository.findById(authorId).ifPresent(author -> {
                if(book.getAuthors().contains(author)){
                    book.getAuthors().remove(author);
                    bookRepository.save(book);
                }
            });
        });
        Book book =bookRepository.findById(bookId).orElse(null);
        return book==null?null:book.getAuthors();
    }
}
